// 在文件顶部添加引用
use crate::controls::control_utils::{remove_from_svchost_group, show_messagebox};
use crate::globals::constants::*;
use crate::internal::regedit::*;
use crate::internal::utils::*;
use std::time::Duration;
use windows_service::{
    Result,
    service::{ServiceAccess, ServiceState},
    service_manager::{ServiceManager, ServiceManagerAccess},
};

/// 卸载服务
pub fn uninstall_service() -> Result<()> {
    // 连接到服务管理器
    let manager_access = ServiceManagerAccess::CONNECT;
    let service_manager = ServiceManager::local_computer(None::<&str>, manager_access)?;

    // 打开服务
    let service_access = ServiceAccess::QUERY_STATUS | ServiceAccess::STOP | ServiceAccess::DELETE;

    // 尝试打开服务，如果服务不存在则直接返回成功
    let service = match service_manager.open_service(SERVICE_NAME, service_access) {
        Ok(service) => service,
        Err(windows_service::Error::Winapi(e)) if e.raw_os_error() == Some(1060) => {
            // ERROR_SERVICE_DOES_NOT_EXIST
            show_uninstall_result_message(true, None);
            return Ok(());
        }
        Err(e) => {
            // Extract error code from windows_service::Error
            let error_code = match &e {
                windows_service::Error::Winapi(io_error) => {
                    io_error.raw_os_error().unwrap_or(0) as u32
                }
                _ => 0,
            };
            show_uninstall_result_message(false, Some(error_code));
            return Err(e);
        }
    };

    // 检查服务状态
    let service_status = service.query_status()?;
    if service_status.current_state != ServiceState::Stopped {
        // 如果服务正在运行，停止它
        let _ = service.stop();

        // 等待服务停止
        let mut attempts = 0;
        while service.query_status()?.current_state != ServiceState::Stopped && attempts < 10 {
            std::thread::sleep(Duration::from_secs(1));
            attempts += 1;
        }
    }

    // 删除服务
    match service.delete() {
        Ok(_) => {}
        Err(e) => {
            // Extract error code from windows_service::Error
            let error_code = match &e {
                windows_service::Error::Winapi(io_error) => {
                    io_error.raw_os_error().unwrap_or(0) as u32
                }
                _ => 0,
            };
            show_uninstall_result_message(false, Some(error_code));
            return Err(e);
        }
    }

    // 从服务组中移除
    let group_result = remove_from_svchost_group();
    if let Err(error) = group_result {
        // 处理错误或记录日志
        println!("从服务组移除失败: {}", error);
    }

    // 检查服务组是否为空，如果为空则删除该键
    let svchost_reg_path = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Svchost";
    match remove_key_if_empty(svchost_reg_path, SERVICE_GROUP) {
        Ok(true) => println!("服务组为空，已删除注册表键"),
        Ok(false) => println!("服务组不为空或键不存在"),
        Err(e) => println!("检查服务组失败: {}", e),
    }

    // 删除服务注册表项
    let reg_path = format!("SYSTEM\\CurrentControlSet\\services\\{}", SERVICE_NAME);
    let reg_path_wide = to_widestring(&reg_path);

    unsafe {
        winapi::um::winreg::RegDeleteKeyW(
            winapi::um::winreg::HKEY_LOCAL_MACHINE,
            reg_path_wide.as_ptr(),
        )
    };

    show_uninstall_result_message(true, None);
    Ok(())
}

/// 显示卸载结果消息
fn show_uninstall_result_message(success: bool, error_code: Option<u32>) {
    let (message, title) = if success {
        (
            format!("服务 {} 卸载成功！", SERVICE_NAME),
            "卸载服务 - 成功".to_string(),
        )
    } else {
        (
            format!(
                "服务 {} 卸载失败！错误代码: {}",
                SERVICE_NAME,
                error_code.unwrap_or(0)
            ),
            "卸载服务 - 失败".to_string(),
        )
    };

    show_messagebox(
        &title,
        &message,
        if success {
            windows::Win32::UI::WindowsAndMessaging::MB_ICONINFORMATION
        } else {
            windows::Win32::UI::WindowsAndMessaging::MB_ICONERROR
        },
    );
}
